package ua.senfiron.finder.searchengine;

import org.apache.commons.lang3.StringEscapeUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ua.senfiron.finder.R;
import ua.senfiron.finder.SearchResultItem;
import ua.senfiron.finder.util.HttpUtilities;
import android.net.Uri;


public class GoogleCustomSearchEngine extends AbstractSearchEngine {
    
    private static final String ENGINE_NAME = "Google Custom Search";
    private static final int ENGINE_ICON_RES_ID = R.drawable.google_icon;
    private static final String API_KEY = "AIzaSyBIqe8i1gwR7E0LWAj2c4hnfzg2t70SsXE";
    private static final String ENGINE_ID = "009541746044356107164:4fl7bhycmfe";
    private static final String BASE_URL = "https://www.googleapis.com/customsearch/v1";


    @Override
    public String getEngineName() {
        return ENGINE_NAME;
    }

    @Override
    public int getIconResID() {
        return ENGINE_ICON_RES_ID;
    }

    @Override
    public int loadResults(int maxCount) {
        
        int count = 0;
        while(count < maxCount)
        {
            if(isCanceled())
                break;
 
            Uri.Builder builder = Uri.parse(BASE_URL).buildUpon();
            builder.appendQueryParameter("key", API_KEY);
            builder.appendQueryParameter("cx", ENGINE_ID);
            builder.appendQueryParameter("alt", "json");
            builder.appendQueryParameter("q", mQuery);

            String jsonResponseString = null;
            jsonResponseString = HttpUtilities.getData(builder.build(), null, null);

            try {

                JSONObject json = new JSONObject(jsonResponseString);
                int totalCount = json.getJSONObject("searchInformation").getInt("totalResults");
                if(totalCount < maxCount)
                {
                    maxCount = totalCount;
                    if(mListener != null)
                        mListener.onMaxResultsCountChanged(maxCount);
                }
                JSONArray results = null;
                if(json.has("items"))
                    results = json.getJSONArray("items");
                else 
                    break;

                for (int j = 0; j < results.length() && count < maxCount; j++, count++) {
                    if(isCanceled())
                        break;
                    
                    JSONObject curResult = results.getJSONObject(j);

                    String title = StringEscapeUtils.unescapeHtml4(curResult
                            .getString("title"));
                    String url = StringEscapeUtils.unescapeHtml4(curResult
                            .getString("link"));
                    
                    SearchResultItem result = 
                            new SearchResultItem(title,url,getEngineName(),getIconResID());
                    if(mListener != null)
                        mListener.onSerachResultLoaded(result);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if(mListener != null)
                    mListener.onMaxResultsCountChanged(count);
                break;
            }
        }
        return count;
    }

}
